package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.CustomerMainOriginal;
import com.isunland.managesystem.entity.CustomerNeed;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.apache.http.Header;
import org.json.JSONException;

public class CustomerVisitFragment extends Fragment implements OnClickListener {
  protected static final String TAG = "CustomerContactFragment";
  public static final String EXTRA_VALUE =
      "com.isunland.managesystem.ui.CustomerVisitFragment.EXTRA_VALUE";
  public static final String EXTRA_CODE = "com.isunland.managesystem.ui.extra_value";
  private static final int REQUEST_lIST = 0;
  private static final int REQUEST_ALTER = 1;

  private static final int REQUEST_CONTACTTIME = 7;
  private static final int REQUEST_TOCUSTOMERPATH = 8;
  private static final int REQUEST_FROMCUSTOMERPATH = 9;
  private static final int REQUEST_APPFILESAVEPATHS = 10;
  private static final int CUSTOMER_NAME = 11;
  private static final int CUSTOMER_NEED = 12;
  protected static final String FAILURE = "0";
  protected static final String SUCCESS = "1";

  private BaseVolleyActivity mActivity;
  private String mId = "";
  private String mCustomerContactType;
  private String mCustomerUnitStatusCode;
  private String mcustomerNeedId;
  private int mDialogType;
  /**
   * 服务器回传的文件在服务器上的路径
   */
  protected String toCustomerPath;
  protected String fromCustomerPath;
  protected String appFileSavePaths;

  private TextView tvCustomerName;
  private TextView tvCustomerAddress;
  private TextView tvSalesName;
  private TextView tvCustomerNeed;
  private TextView tvCustomerStatusText;
  private EditText etFundEstimate;
  private EditText etCustomerNamesPhone;
  private EditText etCustomerPhone;
  private TextView tvContactModeText;
  private TextView tvContactTime;
  private EditText etCommDesc;
  private TextView tvToCustomerPath;
  private TextView tvFromCustomerPath;
  private EditText etOtherDesc;
  private TextView tvAppFileSavePaths;
  private ImageView ivToCustomerPath;
  private ImageView ivFromCustomerPath;
  private ImageView ivAppFileSavePaths;
  private String mcustomerId;
  private CustomerMainOriginal.rCustomerMain mCustomerDetail;

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    mActivity = (BaseVolleyActivity) getActivity();
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setDisplayHomeAsUpEnabled(true);
      actionBar.setTitle(R.string.add_new_contact);
    }
    mCustomerDetail =
        (CustomerMainOriginal.rCustomerMain) getArguments().getSerializable(EXTRA_VALUE);
    mId = UUID.randomUUID().toString();
    mcustomerNeedId = "";
    mCustomerContactType = "";
    mCustomerUnitStatusCode = "";
    appFileSavePaths = "";
    toCustomerPath = "";
    fromCustomerPath = "";
    mcustomerId = mCustomerDetail.getId();
    super.onCreate(savedInstanceState);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_customer_visit, container, false);
    findViews(v);
    return v;
  }

  private void findViews(View v) {
    tvCustomerName = (TextView) v.findViewById(R.id.tv_customerName);
    tvCustomerAddress = (TextView) v.findViewById(R.id.tv_customerAddress);
    tvSalesName = (TextView) v.findViewById(R.id.tv_salesName);
    tvCustomerNeed = (TextView) v.findViewById(R.id.tv_customerNeed);
    tvCustomerStatusText = (TextView) v.findViewById(R.id.tv_customerStatusText);
    etFundEstimate = (EditText) v.findViewById(R.id.et_fundEstimate);
    etCustomerNamesPhone = (EditText) v.findViewById(R.id.et_customerNamesPhone);
    etCustomerPhone = (EditText) v.findViewById(R.id.et_customerPhone);
    tvContactModeText = (TextView) v.findViewById(R.id.tv_contactModeText);
    tvContactTime = (TextView) v.findViewById(R.id.tv_contactTime);
    etCommDesc = (EditText) v.findViewById(R.id.et_commDesc);
    tvToCustomerPath = (TextView) v.findViewById(R.id.tv_toCustomerPath);
    tvFromCustomerPath = (TextView) v.findViewById(R.id.tv_fromCustomerPath);
    etOtherDesc = (EditText) v.findViewById(R.id.et_otherDesc);
    tvAppFileSavePaths = (TextView) v.findViewById(R.id.tv_appFileSavePaths);
    ivToCustomerPath = (ImageView) v.findViewById(R.id.iv_toCustomerPath);
    ivFromCustomerPath = (ImageView) v.findViewById(R.id.iv_fromCustomerPath);
    ivAppFileSavePaths = (ImageView) v.findViewById(R.id.iv_appFileSavePaths);
    setOnClick();
    tvCustomerName.setText(mCustomerDetail.getCustomerName());
    tvCustomerAddress.setText(mCustomerDetail.getDistrictDesc());
  }

  private void setOnClick() {
    tvCustomerStatusText.setOnClickListener(this);
    tvContactModeText.setOnClickListener(this);
    tvContactTime.setOnClickListener(this);
    tvToCustomerPath.setOnClickListener(this);
    tvFromCustomerPath.setOnClickListener(this);
    tvAppFileSavePaths.setOnClickListener(this);
    ivToCustomerPath.setOnClickListener(this);
    ivFromCustomerPath.setOnClickListener(this);
    ivAppFileSavePaths.setOnClickListener(this);
    tvCustomerName.setOnClickListener(this);
    tvCustomerNeed.setOnClickListener(this);
  }

  @Override public void onClick(View v) {

    switch (v.getId()) {

      case R.id.tv_customerStatusText:
        //客户阶段
        showDialog(REQUEST_lIST, CustomerDialogFragment.VALUE_TYPE_CUSTOMER_UNIT_STATE);
        break;
      case R.id.tv_contactModeText:
        //往来方式
        showDialog(REQUEST_lIST, CustomerDialogFragment.VALUE_TYPE_CUSTOMER_TYPE);
        break;
      case R.id.tv_contactTime:
        //往来时间
        showDialog(REQUEST_CONTACTTIME, 0);
        break;
      case R.id.iv_toCustomerPath:
        chooseFile(REQUEST_TOCUSTOMERPATH);
        break;

      case R.id.iv_fromCustomerPath:
        chooseFile(REQUEST_FROMCUSTOMERPATH);
        break;
      case R.id.iv_appFileSavePaths:
        chooseFile(REQUEST_APPFILESAVEPATHS);
        break;
      case R.id.tv_toCustomerPath:
        if (!TextUtils.isEmpty(toCustomerPath)) {
          downFile(toCustomerPath);
        }
        break;
      case R.id.tv_fromCustomerPath:
        if (!TextUtils.isEmpty(fromCustomerPath)) {
          downFile(fromCustomerPath);
        }
        break;
      case R.id.tv_appFileSavePaths:
        if (!TextUtils.isEmpty(appFileSavePaths)) {
          downFile(appFileSavePaths);
        }
        break;
      case R.id.tv_customerNeed:
        //需求
        if (TextUtils.isEmpty(tvCustomerName.getText().toString())) {
          Toast.makeText(getActivity(), "请先选择客户！", Toast.LENGTH_SHORT).show();
        } else {
          //                    Bundle bundle = new Bundle();
          //                    bundle.putSerializable(EXTRA_CODE, mcustomerNeedId);
          //
          //                    DialogFragment dialog1 = null;
          ////                    dialog1 = new CustomerNeedDialogFragment();
          //                    dialog1 = new CustomerNeedListDialogFragment();
          //                    FragmentManager fm1 = getActivity().getSupportFragmentManager();
          //                    dialog1.setTargetFragment(CustomerVisitFragment.this, CUSTOMER_NEED);
          //                    dialog1.setArguments(bundle);
          //                    dialog1.show(fm1, "");
          showDialog(CUSTOMER_NEED, 0);
        }
        break;
      case R.id.tv_customerName:
        //客户名录
        //                DialogFragment dialog = null;
        ////                dialog = new CustomerNameDialogFragment();
        //                dialog = new CustomerNameListDialogFragment();
        //                FragmentManager fm = getActivity().getSupportFragmentManager();
        //                dialog.setTargetFragment(CustomerVisitFragment.this, CUSTOMER_NAME);
        //                dialog.show(fm, "");
        showDialog(CUSTOMER_NAME, 0);
        break;
      default:

        break;
    }
  }

  private void showDialog(int requestCode, int type) {
    mDialogType = type;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    DialogFragment dialog = null;

    switch (requestCode) {

      case REQUEST_lIST:
        //阶段和往来形式
        dialog = CustomerDialogFragment.newInstance(type);
        break;
      case REQUEST_CONTACTTIME:
        //往来时间
        dialog = new BaseYMDTimeDialogFragment();
        break;
      case CUSTOMER_NAME:
        //客户名录
        dialog = new CustomerNameListDialogFragment();
        break;
      case CUSTOMER_NEED:
        //需求
        dialog = CustomerNeedListDialogFragment.newInstance(mcustomerId);
        break;
    }
    dialog.setTargetFragment(this, requestCode);
    dialog.show(fm, "");
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    inflater.inflate(R.menu.menu_confirm, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
      case android.R.id.home:

        getActivity().finish();

        return true;
      case R.id.menu_item_confirm:

        saveCustomerContact();

        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void chooseFile(int requestCode) {
    Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
    intent2.setType("*/*");
    intent2.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(Intent.createChooser(intent2, getString(R.string.chooseFileExplorer)),
        requestCode);
  }

  private String getFile(Intent data) {
    String path1 = FileUtil.getPath(getActivity(), data.getData());
    File mFile = null;
    if (path1 != null) {
      mFile = new File(path1);
    }
    if (null == mFile) {
      Toast.makeText(getActivity(), R.string.fileNotFound, Toast.LENGTH_SHORT).show();
      return "";
    }
    return mFile.getAbsolutePath();
  }

  private void downFile(String serverPath) {
    if (!TextUtils.isEmpty(serverPath)) {
      ExtraDownLoadDialogFragment dialog = ExtraDownLoadDialogFragment.newInstance("", serverPath);
      FragmentManager fm = getActivity().getSupportFragmentManager();
      dialog.show(fm, "");
    }
  }

  private void volleyPostExtra(String resourcefilePath, int requestCode, TextView tvFilePath) {

    if (!TextUtils.isEmpty(resourcefilePath)) {
      new FileNetWorkUtil(getActivity()).upLoadFile(resourcefilePath, ApiConst.URL_UPLOAD_FILE,
          "r_customer_contact_sub ", mId, new myUpLoadHandler(requestCode, tvFilePath), false);
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_lIST && data != null) {
      CustomerDialog customerDialog =
          (CustomerDialog) data.getSerializableExtra(CustomerDialogFragment.EXTRA_VALUE);
      switch (mDialogType) {

        case CustomerDialogFragment.VALUE_TYPE_CUSTOMER_UNIT_STATE:
          mCustomerUnitStatusCode = customerDialog.getId();
          tvCustomerStatusText.setText(customerDialog.getName());
          break;
        case CustomerDialogFragment.VALUE_TYPE_CUSTOMER_TYPE:
          mCustomerContactType = customerDialog.getId();
          tvContactModeText.setText(customerDialog.getName());
          break;

        default:
          break;
      }
    }
    if (requestCode == REQUEST_ALTER) {
      getActivity().setResult(Activity.RESULT_OK);
      getActivity().finish();
    }
    if (requestCode == REQUEST_CONTACTTIME) {
      //往来时间
      Date acquireDate = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      String time = MyDateUtil.dateToString(acquireDate, MyDateUtil.TYPE_DATE);
      tvContactTime.setText(time);
    }
    if (requestCode == REQUEST_TOCUSTOMERPATH) {
      volleyPostExtra(getFile(data), REQUEST_TOCUSTOMERPATH, tvToCustomerPath);
    }
    if (requestCode == REQUEST_FROMCUSTOMERPATH) {
      volleyPostExtra(getFile(data), REQUEST_FROMCUSTOMERPATH, tvFromCustomerPath);
    }
    if (requestCode == REQUEST_APPFILESAVEPATHS) {
      volleyPostExtra(getFile(data), REQUEST_APPFILESAVEPATHS, tvAppFileSavePaths);
    }

    if (requestCode == CUSTOMER_NAME) {
      //名录
      //            CustomerDialog customer = (CustomerDialog) data .getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      //            String name = customer.getName();
      //            mcustomerNeedId = customer.getId();
      //            tvCustomerName.setText(name);//客户名称
      CustomerMainOriginal.rCustomerMain customer =
          (CustomerMainOriginal.rCustomerMain) data.getSerializableExtra(
              CustomerNameListDialogFragment.EXTRA_VALUE);
      String name = customer.getCustomerName();
      mcustomerId = customer.getId();
      tvCustomerName.setText(name);//客户名称
      tvCustomerAddress.setText(customer.getDistrictDesc());
    }

    if (requestCode == CUSTOMER_NEED) {
      //需求
      CustomerNeed customerNeed =
          (CustomerNeed) data.getSerializableExtra(CustomerNeedListDialogFragment.EXTRA_VALUE);
      String need = customerNeed.getNeedProductDesc();
      mcustomerNeedId = customerNeed.getId();
      tvCustomerNeed.setText(need);
      tvSalesName.setText(customerNeed.getSalesName());//销售代表
      tvCustomerStatusText.setText(customerNeed.getCustomerStatusText());//客户阶段
      etFundEstimate.setText(customerNeed.getFundEstimate());//预期投资
      etCustomerNamesPhone.setText(customerNeed.getNearCustomerName());//客户
      etCustomerPhone.setText(customerNeed.getNearCustomerPhone());//联系电话
      tvContactModeText.setText(customerNeed.getCustomerInfoFromText());//往来形式
      tvContactTime.setText(customerNeed.getNearContactDate());//往来时间

      mCustomerContactType = customerNeed.getCustomerInfoFrom();//往来形式
      mCustomerUnitStatusCode = customerNeed.getCustomerStatus();//阶段
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  private void saveCustomerContact() {
    if (!MyUtils.isNetLink(getActivity())) {
      Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_SHORT).show();
      return;
    }
    boolean isEmpty = isEmptyText(etCustomerNamesPhone)
        || isEmptyText(tvContactTime)
        || isEmptyText(etCommDesc)
        || isEmptyText(tvCustomerNeed);

    if (isEmpty) {
      Toast.makeText(getActivity(), R.string.incomplete_message, Toast.LENGTH_SHORT).show();
      return;
    }

    volleyPostAddCustomerContact();
  }

  private boolean isEmptyText(TextView tv) {
    return tv.getText().toString().trim().isEmpty();
  }

  private void volleyPostAddCustomerContact() {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_ADD_CUSTOMER_CONTACT);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    params.put("customerNeedId", mcustomerNeedId);
    params.put("customerStatus", mCustomerUnitStatusCode);
    params.put("fundEstimate", etFundEstimate.getText().toString());
    params.put("customerNamesPhone", etCustomerNamesPhone.getText().toString());
    params.put("customerPhone", etCustomerPhone.getText().toString());
    params.put("contactMode", mCustomerContactType);
    params.put("contactTime", tvContactTime.getText().toString());
    params.put("commDesc", etCommDesc.getText().toString().trim());

    params.put("toCustomerDocname", null == FileUtil.getFileNameByFilePath(toCustomerPath) ? ""
        : FileUtil.getFileNameByFilePath(toCustomerPath));
    params.put("toCustomerPath", toCustomerPath);
    params.put("fromCustomerDocname", null == FileUtil.getFileNameByFilePath(fromCustomerPath) ? ""
        : FileUtil.getFileNameByFilePath(fromCustomerPath));
    params.put("fromCustomerPath", fromCustomerPath);
    params.put("otherDesc", etOtherDesc.getText().toString());
    params.put("appFileNames", null == FileUtil.getFileNameByFilePath(appFileSavePaths) ? ""
        : FileUtil.getFileNameByFilePath(appFileSavePaths));
    params.put("appFileSavePaths", appFileSavePaths);

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          LogUtil.i(TAG, "response=" + arg0);
          SuccessMessage custoomerMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == custoomerMessage || null == custoomerMessage.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = custoomerMessage.getResult();
          if (successType.equals(FAILURE)) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          if (successType.equals(SUCCESS)) {
            ToastUtil.show(R.string.success_operation);

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          LogUtil.e(TAG, "error=" + e, e);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  private class myUpLoadHandler extends AsyncHttpResponseHandler {
    private TextView mtvFilePath;
    private int requestCode;

    public myUpLoadHandler(int requestCode, TextView tvFilePath) {
      this.requestCode = requestCode;
      this.mtvFilePath = tvFilePath;
    }

    @Override public void onStart() {
      MyUtils.showDialogLoading(getActivity());
      super.onStart();
    }

    @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
      MyUtils.dismissDialog();
      ToastUtil.show(R.string.fileUploadFailure);
    }

    @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
      MyUtils.dismissDialog();
      LogUtil.i("arg2==" + new String(arg2));
      try {

        SuccessMessage result = new Gson().fromJson(new String(arg2), SuccessMessage.class);
        if (result == null) {
          MyUtils.dismissDialog();
          ToastUtil.show(R.string.wrong_data);
        }
        if (result != null && result.getResult() != null && result.getResult().equals("1")) {
          // 上传成功,再上传数据
          ToastUtil.show(R.string.fileUploadSuccess);
          String selcurFile = result.getMessage();
          mtvFilePath.setText(FileUtil.getFileNameByFilePath(selcurFile));
          switch (requestCode) {
            case REQUEST_TOCUSTOMERPATH:
              toCustomerPath = selcurFile;
              break;
            case REQUEST_FROMCUSTOMERPATH:
              fromCustomerPath = selcurFile;
              break;
            case REQUEST_APPFILESAVEPATHS:
              appFileSavePaths = selcurFile;
              break;
            default:
              break;
          }
        } else {
          MyUtils.dismissDialog();
          ToastUtil.show(result.getMessage());
        }
      } catch (JsonSyntaxException | Resources.NotFoundException e) {
        e.printStackTrace();
        ToastUtil.show(R.string.fileUploadFailure);
      }
    }
  }

  public static CustomerVisitFragment newInstance(
      CustomerMainOriginal.rCustomerMain customerDetail) {

    Bundle args = new Bundle();
    args.putSerializable(EXTRA_VALUE, customerDetail);
    CustomerVisitFragment fragment = new CustomerVisitFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
